<template>
  <image :src="src" :style="size?`width: ${size}rpx; height: ${size}rpx;`: ''" :mode="mode"/>
</template>
<script setup>
import {Base64} from 'js-base64'
import {computed} from 'vue'

const dProps = defineProps({
  size: {
    type: [Number, String],
    default: 45
  },
  src: [String],
  mode: [String],
  props: [Object]
})

const src = computed(() => {
  if (dProps.props && /\.svg$/.test(dProps.src)) {
    // 先获取svg源码字符串，替换 file="#ffff"  stroke='#FFFFFF' 颜色这个属性，再将这个字符串转化为base64，达到修改颜色的目的
    let baseStr = wx.getFileSystemManager().readFileSync(dProps.src, 'binary')
    if (dProps.props) {
      for (const prop in dProps.props) {
        baseStr = replaceStr(baseStr, prop, dProps.props[prop])
      }
    }
    return 'data:image/svg+xml;base64,' + Base64.encode(baseStr)
  }
  return dProps.src
})

function replaceStr(baseStr, prop, newProps) {
  const regExp = new RegExp(prop + '="[^"]*"', 'g')
  const strArr = baseStr.split(regExp)
  const oldColorArr = baseStr.match(regExp)
  const newColorArr = newProps.split(',')
  for (let i = 0; i < newColorArr.length; i++) {
    const color = newColorArr[i]
    if (color && oldColorArr && oldColorArr[i]) {
      oldColorArr[i] = `${prop}="${color}"`
    }
  }
  let str = ''
  for (let i = 0; i < strArr.length; i++) {
    str += (strArr[i] + (oldColorArr && oldColorArr[i] ? oldColorArr[i] : ''))
  }
  return str
}

</script>
